import {app, BrowserWindow, ipcMain} from 'electron'
import path from 'path'
import {ApiRequest, requestApi} from './api'

const isDev = process.env.NODE_ENV === 'development'

function createWindow() {
  const win = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
      preload: path.join(app.getAppPath(), 'dist', 'electron', 'preload.js'),
      // 安全加固：禁用 Node 集成并启用上下文隔离
      nodeIntegration: false,
      contextIsolation: true,
      // 仅允许通过 preload 暴露的安全 API 访问主进程
    }
  })

  if (isDev) {
    const devUrl = process.env.VITE_DEV_SERVER_URL || 'http://localhost:5174'
    win.loadURL(devUrl)
    win.webContents.openDevTools()
  } else {
    win.loadFile(path.join(app.getAppPath(), 'dist', 'renderer', 'index.html'))
  }
}

app.whenReady().then(() => {
  createWindow()
  // API 请求走主进程，避免跨域
  ipcMain.handle('api:request', async (_event, req: ApiRequest) => {
    return await requestApi(req)
  })
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})